﻿using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.AspNetCore.SignalR;
using Pomelo.AspNetCore.TimedJob;
using Iot.Models;
using Iot.Hubs;
using System;

namespace Iot.Jobs
{
    public class AutoHubJob : Job
    {
        private readonly ILogger<AutoHubJob> _logger;
        private static IClientWorker? _clientWorker;

        public AutoHubJob(IServiceProvider provider)
        {
            _logger = provider.GetRequiredService<ILogger<AutoHubJob>>();
            _clientWorker = provider.GetRequiredService<IClientWorker>();
        }

        /// <summary>
        /// 每 {Interval}ms 进行一次健康检查
        /// </summary>
        /// <returns></returns>
        [Invoke(Begin = "2000-10-01 00:00:00", Interval = 1000 * 10, SkipWhileExecuting = false)]
        public async Task RunAsync()
        {
            var url = $"{AppData.AppConfig.BaseUrl}{MessageHub.HubUrl}";
            //_logger.LogError($"{url} => {AppData.HUB?.State}");
            if (AppData.HUB is null)
            {
                _logger.LogError($"Connect......");
                AppData.HUB = new HubConnectionBuilder()
                    .WithUrl(url)
                    .WithStatefulReconnect()
                    .Build();

                await AppData.HUB.StartAsync();
            }
            else
            {
                if (AppData.HUB.State != HubConnectionState.Connected)
                {
                    //_logger.LogError($"Reconnect......");
                    await AppData.HUB.StartAsync();
                }
            }
        }
    }
}
